package com.ls.fw.mvc.springmvc.support.listener;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.ServletContextAware;

import com.ls.fw.commons.config.property.FwPropertyPlaceholderConfigurer;
import com.ls.fw.commons.core.utils.collections.CollectionUtils;
import com.ls.fw.commons.core.utils.collections.MapUtils.CollectionMapper;
import com.ls.fw.commons.license.KeystoreInfo;
import com.ls.fw.commons.license.LicenseController;
import com.ls.fw.commons.license.PrincipalInfo;
import com.ls.fw.commons.license.support.ExceptionHandler;
import com.ls.fw.commons.license.support.LicenseCheckTimer;
import com.ls.fw.commons.license.support.TimeUnit;
import com.ls.fw.commons.security.help.KeyStoreTool;
import com.ls.fw.commons.spring.SpringContextHolder;
import com.ls.fw.web.core.support.WebContext;

public class WebListener implements ApplicationListener<ContextRefreshedEvent> ,ServletContextAware{
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	private final LicenseController c = LicenseController.newInstance();

	@Override
	public void onApplicationEvent(final ContextRefreshedEvent event) {
		
	}	
	
	private void load(final ServletContext servletContext){
		List<FwPropertyPlaceholderConfigurer> configurers = SpringContextHolder.findBeansByType(FwPropertyPlaceholderConfigurer.class);
		if(configurers!=null){
			for (FwPropertyPlaceholderConfigurer fwPropertyPlaceholderConfigurer : configurers) {
				Map<String, String> map = fwPropertyPlaceholderConfigurer.getPropsMap();
				if(map != null){
					CollectionUtils.traversal(map, new CollectionMapper() {
						
						@Override
						public boolean next(Object key, Object value) {
							WebContext.map.put(String.valueOf(key), String.valueOf(value));
							servletContext.setAttribute(String.valueOf(key).replace(".", "_"), String.valueOf(value));
							return true;
						}
					});
				}
			}
		} 
		WebContext.map.put("realPath", servletContext.getRealPath("/").replaceFirst("/", ""));
		WebContext.map.put("contextPath", servletContext.getContextPath());
		boolean ok  = true;
		try {
			//ok  = check();
		} catch (Exception e) {
			ok  = false;
		}finally{
			if(!ok){
				System.out.println("授权验证失败！请联系管理员！");
				System.exit(-1);
			}
		}
	}

	private boolean check() throws Exception{
		c.setAppName(WebContext.map.get("license.appName"));
	    PrincipalInfo  principalInfo  = new  PrincipalInfo();
	    principalInfo.setCity(WebContext.map.get("license.city"));
	    principalInfo.setCountry(WebContext.map.get("license.country"));
	    principalInfo.setFirstName(WebContext.map.get("license.firstName"));
	    principalInfo.setLastName(WebContext.map.get("license.lastName"));
	    principalInfo.setState(WebContext.map.get("license.state"));
	    String privateStorePass =  WebContext.map.get("license.privateStorePass"); 
	    String publicStorePass =  WebContext.map.get("license.publicStorePass");
		String privateKeyPass =  WebContext.map.get("license.privateKeyPass");
		KeyStoreTool  t = new KeyStoreTool(privateStorePass,publicStorePass,privateKeyPass,principalInfo);
		KeystoreInfo keystoreInfo = null;
		keystoreInfo = new KeystoreInfo();
		keystoreInfo.setAlias(t.getPublicCertStoreAlias());
		keystoreInfo.setKeystoreFilename(t.getPublicKeyStorePath());
		keystoreInfo.setKeyPassword(t.getPrivateKeyPass());
		keystoreInfo.setKeystorePassword(t.getPublicStorePass());
		c.setKeystoreInfo(keystoreInfo);
		String checkMacStr = WebContext.map.get("license.checkMac");
		c.setCheckMac(false);
		if("true".equalsIgnoreCase(checkMacStr)){
			c.setCheckMac(true);
		}
		c.setLicenseFilename(WebContext.map.get("license.path"));
		c.installLicense(true);
		c.verifyLicense();
		Date now = new Date();
        Calendar cal = Calendar.getInstance(); // creates calendar
        cal.setTime(now); // sets calendar time/date
        cal.add(Calendar.MINUTE, -1); // adds one minute
        int s = 18;
		LicenseCheckTimer timer = new LicenseCheckTimer(cal.getTime(),TimeUnit.MINUTE
				, s, c, new ExceptionHandler() {
			@Override
			public void handler(Exception e) {
				//e.printStackTrace();
			}

			@Override
			public void invalid() {
				//System.out.println("invalid!");
				System.out.println("授权文件失效！请联系管理员！");
				System.exit(-1);
			}

			@Override
			public void info(int doTimes, int moreTimes) {
				//System.out.println("doTimes:"+doTimes+",moreTimes="+moreTimes);
			}
		});
		timer.start();
		return true;
	}

	@Override
	public void setServletContext(final ServletContext servletContext) {
		// TODO Auto-generated method stub
		//需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				load(servletContext);
			}
		});
		thread.setDaemon(true);
		thread.start();
	}
	
}